#!/usr/bin/python3
# coding: utf-8
# 表单
# file: forms.py
from wtforms import form, fields, validators

class LoginForm(form.Form):
	'登录表单'
	login = fields.StringField(label='用户名', validators=[validators.required()])
	password = fields.PasswordField(label='密码', validators=[validators.required()])

	def validate_login(self, field):
		user = self.get_user()

		if user is None:
			raise validators.ValidationError('用户名不能为空')

		# we're comparing the plaintext pw with the the hash from the db
		if not check_password_hash(user.password, self.password.data):
		# to compare plain text passwords use
		# if user.password != self.password.data:
			raise validators.ValidationError('无效密码')

	def get_user(self):
		return db.session.query(User).filter_by(login=self.login.data).first()

class RegistrationForm(form.Form):
	'注册表单'
	login = fields.StringField(label='用户名', validators=[validators.required()])
	email = fields.StringField(label='邮箱')
	password = fields.PasswordField(label='密码', validators=[validators.required()])

	def validate_login(self, field):
		if db.session.query(User).filter_by(login=self.login.data).count() > 0:
			raise validators.ValidationError('用户名已经存在')

